package com.cmccgz.udacs_landlord_webapp.observers;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.content.ContextCompat;

import com.cmccgz.udacs_landlord_webapp.interfaces.OnGetSmsKeyListenter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hzx07 on 2017/8/1.
 */

public class SmsObserver extends ContentObserver {

    private final Context context;
    private final OnGetSmsKeyListenter listener;
    private final Handler handler;

    public SmsObserver(Handler handler, Context context, OnGetSmsKeyListenter listener) {
        super(handler);
        this.context = context;
        this.listener = listener;
        this.handler = handler;
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        new Thread(new Runnable() {
            @Override
            public void run() {
                int isHasPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS);
                if (isHasPermission != PackageManager.PERMISSION_GRANTED)
                    return;
                Cursor cursor = context.getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
                if (cursor != null && cursor.getCount() > 0) {
                    String body = "";
                    String address = "";
                    cursor.moveToFirst();
                    body = cursor.getString(cursor.getColumnIndex("body"));
                    address = cursor.getString(cursor.getColumnIndex("address"));
                    // TODO 获取短信的全部信息
                    // String receiveTime =
                    // cursor.getString(cursor.getColumnIndex(""));
                    if (!cursor.isClosed()) {
                        cursor.close();
                    }
                    final String dynamicPassword = getDynamicPassword(body);
                    if (listener != null && address != null && body.contains("门禁APP")) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onChange(dynamicPassword);
                            }
                        });
                    }
                }
            }
        }).start();
    }

    /**
     * @param str
     * @return
     */
    private String getDynamicPassword(String str) {
        Pattern continuousNumberPattern = Pattern.compile("//d{6}");
        Matcher m = continuousNumberPattern.matcher(str);
        String dynamicPassword = "";
        if (m.find()) {
            dynamicPassword = m.group();
        }
        return dynamicPassword;
    }
}
